package GearCommands;

import Connections.Peer;
import Gear.Factory;
import Gear.Gear;

import java.io.IOException;
import java.lang.reflect.Array;
import java.nio.file.FileSystems;
import java.nio.file.Files;

/**
 * Implementation of the user command rm.
 * Removes safely a file from the gear path.
 *
 * @author Davi Mendes
 */
public class GearCommandRm implements GearCommand {

    @Override
    public void execute(String[] args, Gear gear) {
        try {
            if (args.length < 2) throw new IllegalArgumentException("Too few arguments to rm command.");
            Factory.getInstance().getLocalFileMutex().acquire(args[1]);
            if (Peer.getInstance().removeFile(args[1]))
                Files.delete(FileSystems.getDefault().getPath(Factory.getInstance().getSettings().getGearPath().toString(), (String) Array.get(args, 1)));
            else System.out.println("This file is busy or not exists, try again later.");
            Factory.getInstance().getLocalFileMutex().release(args[1]);

        } catch (IOException ex) {
            System.out.println("Error on deleting operation.");
        } catch (IllegalArgumentException ex) {
            System.out.println(ex.getMessage());
        }
    }

}
